package com.house.web.controller;

import java.io.IOException;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.house.biz.MessageBiz;
import com.house.biz.UserBiz;
import com.house.entity.Message;
import com.house.entity.User;

@Controller
public class UserController {
	@Autowired
	private UserBiz userBiz;
	@Autowired
	private MessageBiz messageBiz;
	
	@RequestMapping("/login")
	public String login(){
		return "login";
	}
	
	@RequestMapping("/register")
	public String register(){
		return "register";
	}
	
	@RequestMapping("/loginHouse")
	public String loginHouse(Model model,String userName,String passWord,HttpServletRequest request,String returnUrl){
		User user=userBiz.login(userName, passWord);
		if(user!=null){
			request.getSession().setAttribute("user", user);
			if (returnUrl != null && !returnUrl.equals("")) {
				return "redirect:"+returnUrl;
			}else{
				int state=0;
				List<Message> messages =messageBiz.getMessagesByTid(user.getId());
				if(messages.size()>0){
					state =1;
				}
				request.getSession().setAttribute("state", state);
				if(user.getIsAdmin()==1){
					return "redirect:admin/admin_default";
				}else{
					return "redirect:index";
				}
			}
		}else{
			model.addAttribute("error", "用户或密码错误");
			return "login";
		}
		
	}
	
	@RequestMapping("/checkUserName")
	public void checkUserName(String userName, HttpServletResponse response)
			throws IOException {
		User user = userBiz.getByUserName(userName);
		response.getWriter().print(user != null);
	}

	
	@RequestMapping("/registerUser")
	public String registerUser(Model model,User user){
		user.setIsInUse(1);
		user.setIsAdmin(0);
		
		userBiz.addUse(user);
		
		return "redirect:login";
	}
	
	@RequestMapping("/message")
	public String message(int fid,int tid,Model model){
		model.addAttribute("fid", fid);
		model.addAttribute("tid", tid);
		return "message";
	}
	@RequestMapping("/getMessage")
	public String getMessage(int id,Model model){
		List<Message> messages =messageBiz.getMessagesByTid(id);
		model.addAttribute("messages", messages);
		return "getMessage";
	}
	
	@RequestMapping("/addMessage")
	public String addMessage(int fid,int tid,String message){
		Message me =new Message();
		me.setCreateTime(new Date());
		me.setContent(message);
		me.setFromUser(userBiz.getUserById(fid));
		me.setToUser(userBiz.getUserById(tid));
		messageBiz.addMessage(me);
		return "redirect:index";
	}
	
}
